package com.cbtx.module_sp.ui

import android.text.TextUtils
import com.cbtx.module.base.http.HttpManager
import com.txcb.lib.base.utils.FileUtils
import com.txcb.lib.base.utils.LogUtil
import com.txcb.lib.base.utils.MD5Util
import java.io.File

class DownloadUtil {


    fun loadVideo(downloadUrl: String) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return
        }
        val indext = downloadUrl.lastIndexOf("/") + 1
        val fileName = downloadUrl.substring(indext)
        val filePath: String = FileUtils.getDownloadDir()

        val downloadName = MD5Util.setString(downloadUrl)
        val downloadSavePath = "$filePath/$downloadName"
        val allPath = "$filePath/$fileName"

        LogUtil.d("============================================================================")
        LogUtil.d("downloadUrl${downloadUrl}")
        LogUtil.d("fileName${fileName}")
        LogUtil.d("filePath${filePath}")
        LogUtil.d("downloadName${downloadName}")
        LogUtil.d("downloadSavePath${downloadSavePath}")
        LogUtil.d("allPath${allPath}")
        LogUtil.d("============================================================================")

        //
        val videoFile = File(allPath)
        if (videoFile.exists()){
//            mVideoPath.value = allPath
            return
        }
        HttpManager.getInstance("",null)
            .downloadFile(downloadUrl, filePath, downloadName, object : HttpManager.OnDownloadListener {
                override fun onDownloadSuccess(path: String?) {
                    LogUtil.d("onDownloadSuccess:")

                    //下载成功后修改文件名（md5改成正式的）
                    val videoPath = FixFileName(downloadSavePath,fileName)

//                    mVideoPath.value = videoPath
                }

                override  fun onDownloading(progress: Int) {
                    LogUtil.d("progress:$progress")
                }

                override fun onDownloadFailed() {
                    LogUtil.d("onDownloadFailed:")
                }
            })
    }


    /**
     * 2 * 通过文件路径直接修改文件名
     * 3 *
     * 4 * @param filePath 需要修改的文件的完整路径
     * 5 * @param newFileName 需要修改的文件的名称 （如果不是文件夹，则需要带后缀名)
     * 6 * @return
     * 7
     */
    fun FixFileName(filePath: String, newFileName: String): String? {
        var newFileName = newFileName
        val f = File(filePath)
        if (!f.exists()) { // 判断原文件是否存在（防止文件名冲突）
            return null
        }
        newFileName = newFileName.trim { it <= ' ' }
        if (TextUtils.isEmpty(newFileName)) // 文件名不能为空
            return null
        var newFilePath: String? = null
        newFilePath = filePath.substring(0, filePath.lastIndexOf("/"))
        val file = File(newFilePath)
        if (!file.exists()) {
            file.mkdirs()
        }
        val nf = File(newFilePath, newFileName)
        try {
            f.renameTo(nf) // 修改文件名
        } catch (err: Exception) {
            err.printStackTrace()
            LogUtil.d("FixFileName Exception:$err")
            return null
        }
        return nf.path
    }



}